using SqlSugar;

namespace sgf.server
{
    public class MysqlClient
    {
        private SqlSugarClient db;

        public MysqlClient(string url, int port, string database, string user, string password)
        {
            db = new SqlSugarClient(new ConnectionConfig()
            {
                DbType = DbType.MySql,
                ConnectionString = $"server={url};Port={port},Database={database};Uid={user};Pwd={password}",
                IsAutoCloseConnection = true
            });
            // //其他配置
            // Port=3305 指定端口号 不指定是默认
            // Charset= 设置编码 
            // AllowLoadLocalInfile=true 启用bulkcopy
        }

        //建表
        public void InitTables<T>()
        {
            db.CodeFirst.InitTables<T>();
        }

        //查询表的所有
        public List<T> QueryAll<T>() where T : class, new()
        {
            return db.Queryable<T>().ToList();
        }

        //查询一条
        public T QueryOne<T>(int id) where T : class, new()
        {
            return db.Queryable<T>().InSingle(id);
        }

        public int QueryCount<T>() where T : class, new()
        {
            return db.Queryable<T>().Count();
        }
        

        //插入
        public void Insert<T>(T obj) where T : class, new()
        {
            db.Insertable(obj).ExecuteCommand();
        }

        //更新
        // Db.Updateable(new Student() { Id = 1, SchoolId = 2, Name = "jack2" }).ExecuteCommand();
        public void Update<T>(T obj) where T : class, new()
        {
            db.Updateable(obj).ExecuteCommand();
        }

        //删除
        public void Delete<T>(T obj) where T : class, new()
        {
            db.Deleteable(obj).ExecuteCommand();
        }
    }
}